#!/usr/bin/perl
# file: gab2.pl
# usage: gab2.pl host [port]
# forking Tcp network client

use strict;
use IO::Socket qw(:DEFAULT :crlf);

my $host = shift or die "Usage: gab2.pl host [port] \n";
my $port = shift || 'echo';

my $socket = IO::Socket::INET->new("$host:$port") or die $@;
my $child = fork();
die "can't fork $!" unless defined $child;

if($child){
    $SIG{CHLD} = sub{ exit 0 };
    user_to_host($socket);
    $socket->shutdown(1);
    sleep;      
# 考虑到美观问题，可能父进程直接终止后子进程还会接收数据并向标准输出打印。
# 等待子进程完全停止后发送一个 CHLD 信号，父进程探测到 CHLD 后停止。
}else{
    host_to_user($socket);
    warn "connection closed by foreign host. \n";
}

sub user_to_host{
    my $s = shift;
    while(<>){
        chomp;
        print $s $_,CRLF;
    }
}

sub host_to_user{
    my $s = shift;
    $/ = CRLF;
    while (<$s>){
        chomp;
        print $_,"\n";
    }
}